//
//  QRCodeViewController.swift
//  WeiBoSwift
//
//  Created by Jacky Sun on 16/4/21.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController, UITabBarDelegate {
    ///  容器的高度约束
    @IBOutlet weak var containerHeightCst: NSLayoutConstraint!
    /// 冲击波距离顶部的高度
    @IBOutlet weak var waveTopCst: NSLayoutConstraint!
    
    /// 冲击波视图
    @IBOutlet weak var shockWaveImg: UIImageView!
    
    @IBOutlet weak var customTabbar: UITabBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        shockWaveImg.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
        customTabbar.selectedItem = customTabbar.items![0]
        customTabbar.delegate = self
    }


    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
       //  开始冲击波动画
        startAnimation()
        
        // 开始扫描
        startScan()
        }
    
    /**
     我的名片
     
     - parameter sender: <#sender description#>
     */
    @IBAction func businessCardClick(sender: AnyObject) {
        
    shockWaveImg.layer.removeAllAnimations()

      let vc = GenerateQrCodeController()
        navigationController?.pushViewController(vc, animated: true)
        
    }
    
    @IBAction func leftCloseClick(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    private func startScan() {
        
        if !sessions.canAddInput(deviceInput){
            return
        }
        if !sessions.canAddOutput(deviceOutPut) {
            return
        }
        
        // 将输入和输出设备添加到回话里面
        sessions.addInput(deviceInput)
        sessions.addOutput(deviceOutPut)
       // print(deviceOutPut.availableMetadataObjectTypes)
        
        // 注意: 设置能够解析的数据类型, 一定要在输出对象添加到会员之后设置, 否则会报错
        deviceOutPut.metadataObjectTypes = deviceOutPut.availableMetadataObjectTypes
        // 5.设置输出对象的代理, 只要解析成功就会通知代理
        deviceOutPut.setMetadataObjectsDelegate(self, queue:dispatch_get_main_queue())
        // 添加预览图层
        view.layer.insertSublayer(preview, atIndex: 0)
        // 开始扫描
         sessions.startRunning()
    }
    
    
    private func startAnimation() {
        // 移除所有的动画
     //   shockWaveImg.layer.removeAllAnimations()
        
        
//        waveTopCst.constant = -containerHeightCst.constant
//        shockWaveImg.layoutIfNeeded()
//        
//        UIView.animateWithDuration(2.0) {
//            self.waveTopCst.constant  = self.containerHeightCst.constant
//            self.shockWaveImg.layoutIfNeeded()
//            UIView.setAnimationRepeatCount(MAXFLOAT)
//
//        }
        
        
        let anim = CABasicAnimation(keyPath: "position")
     //   let centerX = UIScreen.mainScreen().bounds.size.width * 0.5
        anim.fromValue =  NSValue(CGPoint: CGPoint(x: 150, y: -containerHeightCst.constant))
        anim.toValue =  NSValue(CGPoint: CGPoint(x: 150, y: containerHeightCst.constant))
        anim.duration = 2.0
       // anim.removedOnCompletion = false
        anim.fillMode = kCAFillModeForwards
        anim.repeatCount = MAXFLOAT
        shockWaveImg.layer.addAnimation(anim, forKey: nil)
    }
    
    
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        if(item.tag == 22){
            title = "二维码"
            containerHeightCst.constant = 300
        }
        else{
            title = "条形码"
            containerHeightCst.constant = 150
        }
        
        startAnimation()

    }
    
    
    //MARK: - 懒加载  回话
    private lazy var sessions : AVCaptureSession = AVCaptureSession()
    
    //拿到输入设备
    private lazy var deviceInput: AVCaptureDeviceInput? = {
        // 获取摄像头
      let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        
        do{
            // 创建输入对象
            let input = try  AVCaptureDeviceInput(device: device)
            return input
        }catch{
            print(error)
            return nil
        }
    }()
    
     /// 输出设备
    private lazy var deviceOutPut : AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
   private lazy var preview : AVCaptureVideoPreviewLayer = {
        let layer = AVCaptureVideoPreviewLayer(session: self.sessions)
        layer.frame = UIScreen.mainScreen().bounds
        return layer
    }()
    
    
}



extension QRCodeViewController : AVCaptureMetadataOutputObjectsDelegate {
    
    
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!){
        
        print(metadataObjects.last?.stringValue)
    }
}
